﻿using Avocado.Seckill.IQIYI.input;
using Avocado.Seckill.IQIYI.Res;
using Newtonsoft.Json;
using QRCoder;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Reflection.Emit;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using static System.Windows.Forms.LinkLabel;

namespace Avocado.Seckill.IQIYI
{
    public partial class MainFrm : Form
    {

        private Logintoken logintoken = new Logintoken();
        private LoginResult loginResult = new LoginResult();
        private bool TimerIsRun = false;
        private bool MsTimerIsRun = false;


        public MainFrm()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();

        }
        //秒杀地址
        // get https://act.vip.iqiyi.com/supermk/seckill/action/seckill?P00001=03EK6YNm3A10hod2bLbNm1WFc8bWx6O90m3LrTuim1EVs3tfxUm3Gffm2kAoodo3m1unuBLbd98&dfp&qyid=2rxglf1ji5xwoa79v35ztsi7&version&agentType=13&platform=97ae2982356f69d8&ptid=02020031010000000000&fv=b3b9274a0eb0aafd&appname=vipSeckill&messageId=15d75f6379dc41c4d1a723a817beef40&_=1700222400012&code=942d332be0ba79e1
        //获取token 地址
        // post https://passport.iqiyi.com/apis/qrcode/gen_login_token.action?agenttype=1&surl=1
        //二维码内容 由url返回

        private void SetQRCode(string link)
        {
            //PictureBox pictureBox = new PictureBox();
            if (string.IsNullOrWhiteSpace(link))
            {
                picQrcode.Image = null;
                return;
            }
            QRCodeGenerator generator = new QRCodeGenerator();
            QRCodeData data = generator.CreateQrCode(link, QRCodeGenerator.ECCLevel.M);    //qrCode是二维码内容，ECCLevel用于设置容错率
            QRCode code = new QRCode(data);
            //定义二维码中央水印图标，文件路径一定要是绝对路径，如果是Web工程，可用Server.MapPath函数获取绝对路径
            Bitmap qrImage = code.GetGraphic(10, Color.Black, Color.White, null, 15, 6, true);
            //获得含水印的二维码图像信息，如不需要水印可以调用另外函数：Bitmap qrImage = code.GetGraphic(10);

            picQrcode.Image = qrImage;
            if (!TimerIsRun)
            {
                timer1.Start();
                TimerIsRun = true;
            }
        }

        private async void MainFrm_Load(object sender, EventArgs e)
        {
            btnTest.Enabled = false;
            btnStart.Enabled = false;
            btnStop.Enabled = false;
            //await LodingQRCode();
            await LodingSeckillCode();
        }

        private async Task LodingSeckillCode()
        {
            using HttpClient httpClient = new HttpClient();
            HttpContent httpContent = JsonContent.Create<GetIQIYISeckillsInput>(new GetIQIYISeckillsInput
            {
                EndTime = DateTime.Now.AddDays(1).Date,
                StartTime = DateTime.Now.AddHours(-1)
            });
            var res = await httpClient.PostAsync("https://api.tangtu.top/api/tangtu/seckill/get-iqiyi", httpContent);
            if (res.IsSuccessStatusCode)
            {

                var aa = await res.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<Result<List<IQIYISeckill>>>(aa);
                if (result?.data != null)
                {
                    cbSeckill.DataSource = result.data;
                    cbSeckill.ValueMember = "Code";
                    cbSeckill.DisplayMember = "Name";
                }
            }

        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnRefresh_Click(object sender, EventArgs e)
        {
            await LodingSeckillCode();
        }
        private async Task LodingQRCode()
        {
            using HttpClient httpClient = new HttpClient();
            var res = await httpClient.PostAsync("https://passport.iqiyi.com/apis/qrcode/gen_login_token.action?agenttype=1&surl=1", null);
            if (res.IsSuccessStatusCode)
            {

                var result = await res.Content.ReadFromJsonAsync<Result<Logintoken>>();
                if (result?.data != null)
                    logintoken = result.data;
                SetQRCode(result?.data?.url);
            }
        }

        private async Task LodingLoginStatu()
        {
            if (logintoken == null)
                return;
            using HttpClient httpClient = new HttpClient();
            var res = await httpClient.PostAsync($"https://passport.iqiyi.com/apis/qrcode/is_token_login.action?agenttype=1&token={logintoken.token}", null);
            if (res.IsSuccessStatusCode)
            {
                var result = await res.Content.ReadFromJsonAsync<Result<LoginResult>>();
                if (result.code == "P00501" || result.msg == "登录token已经过期")
                {
                    lbMsg.Text = $"{result.msg},请点击二维码刷新重新登录";
                    timer1.Stop();
                    TimerIsRun = false;
                }
                else if (result.code == "A00000" || result.data != null)
                {
                    loginResult = result.data;
                    lbMsg.Text = $"登录成功";
                    txtToken.Text = loginResult.authcookie;
                    timer1.Stop();
                    TimerIsRun = false;
                    this.Text = $"爱奇艺秒杀-{loginResult.userinfo.nickname}";
                    await LodingUserImage();
                    btnTest.Enabled = true;
                    btnStart.Enabled = true;
                    btnStop.Enabled = true;
                }
                else
                    lbMsg.Text = result.msg;
            }
        }

        private async Task LodingUserImage()
        {
            using HttpClient httpClient = new HttpClient();
            picQrcode.Image = Image.FromStream(await httpClient.GetStreamAsync(loginResult.userinfo.icon));
            picQrcode.Enabled = false;
        }



        private async void timer1_Tick(object sender, EventArgs e)
        {
            await LodingLoginStatu();
        }

        private async void picQrcode_Click(object sender, EventArgs e)
        {
            await LodingQRCode();
        }

        int index = 0;
        int maxIndex = 30;

        private async Task Seckill(bool isRun, int indexI = 0)
        {
            do
            {
                try
                {
                    IQIYISeckill seckill = (IQIYISeckill)(cbSeckill.SelectedItem);

                    using HttpClient httpClient = new HttpClient();

                    IqiyiBaseParam iqiyiBaseParam = new IqiyiBaseParam()
                    {
                        P00001 = loginResult.authcookie
                    };
                    var dic = IqiyiFun.ObjectToMap(iqiyiBaseParam);
                    dic.Add("code", seckill.Code);
                    string url = $"https://act.vip.iqiyi.com/supermk/seckill/action/seckill?{IqiyiFun.DicToGetString(dic)}";
                    var res = await httpClient.PostAsync(url, null);
                    if (res.IsSuccessStatusCode)
                    {
                        TimeSpan difference = (DateTime.Now - res.Headers.Date).Value;
                        await SetTxtMsg($"毫秒：{difference.TotalMilliseconds}");
                        var result = await res.Content.ReadFromJsonAsync<Result<object>>();
                        if (result?.msg == null ||
                            result.msg.Contains("恭喜您") ||
                            result.msg.Contains("秒杀成功") ||
                            result.msg.Contains("已超出秒杀数量上限") ||
                            result.msg.Contains("积分不足") ||
                            result.msg.Contains("已结束") ||
                            result.msg.Contains("您已抢过本次福利商品") ||
                            result.msg.Contains("抢光了"))
                        {
                            await SetTxtMsg($"{seckill.Name}_{indexI}_{result?.msg}");
                            await SetTxtMsg(JsonConvert.SerializeObject(result));
                            MsTimerIsRun = false;
                            return;
                        }
                        else
                        {
                            //await SetTxtMsg(JsonConvert.SerializeObject(result));
                            await SetTxtMsg($"{seckill.Name}_{indexI}_{result?.msg}");
                        }
                    }
                    Random random = new Random();
                    //await Task.Delay(random.Next(10, 50));

                    //await Task.Delay(1);
                    if (DateTime.Now > seckill.SeckillTime.AddSeconds(8))
                    {
                        await SetTxtMsg($"哈哈_已经过时8秒了，不用抢了肯定没了");
                        MsTimerIsRun = false;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    await SetTxtMsg($"{ex.Message}");
                    return;
                }
            }
            while (isRun);
        }

        private async Task SetTxtMsg(string msg)
        {
            if (txtMsg.InvokeRequired)
            {
                txtMsg.Invoke((string p) =>
                {
                    txtMsg.AppendText($"{DateTime.Now.ToString("HH:mm:ss:fff")}:{p}\r\n");
                }, msg);
            }
            else { txtMsg.AppendText($"{DateTime.Now.ToString("HH:mm:ss:fff")}:{msg}\r\n"); }
        }

        private async void msTimer_Tick(object sender, EventArgs e)
        {
            IQIYISeckill seckill = (IQIYISeckill)(cbSeckill.SelectedItem);
            if (DateTime.Now < seckill.SeckillTime.AddSeconds(-2))
            {
                index++;
                if (index > maxIndex)
                {
                    await SetTxtMsg($"当前还没有到点呢");
                    index = 0;
                }
                return;
            }
            if (DateTime.Now > seckill.SeckillTime.AddSeconds(8))
            {
                await SetTxtMsg($"已经过时8秒了，不用抢了肯定没了");
                msTimer.Stop();
                MsTimerIsRun = false;
                return;
            }
            msTimer.Stop();
            for (int i = 0; i < 100; i++)
            {
                await SetTxtMsg($"启动线程{i}");
                int c = i;
                _ = Task.Run(async () =>
                {
                    await Seckill(true, c);
                });

                //await Task.Delay(1);
            }
        }

        private async void btnTest_Click(object sender, EventArgs e)
        {
            _ = Task.Run(async () => { await Seckill(false); });
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (MsTimerIsRun)
            {
                return;
            }
            msTimer.Start();
            MsTimerIsRun = true;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            msTimer.Stop();
            MsTimerIsRun = false;
        }

        private async void btnNewAccount_Click(object sender, EventArgs e)
        {
            await Logout();
            logintoken = new Logintoken();
            loginResult = new LoginResult();
            timer1.Stop();
            msTimer.Stop();
            TimerIsRun = false;
            MsTimerIsRun = false;
            picQrcode.Enabled = true;
            btnTest.Enabled = false;
            btnStart.Enabled = false;
            btnStop.Enabled = false;
            this.Text = $"爱奇艺秒杀";
            await LodingQRCode();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtMsg.Text = "";
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        private async Task Logout()
        {
            if (string.IsNullOrWhiteSpace(loginResult.authcookie))
            {
                return;
            }
            string url = $"https://passport.iqiyi.com/apis/user/logout.action?authcookie={loginResult.authcookie}&agenttype=1&noredirect=1&ptid=01010021010000000000&opt_type=4";
            using HttpClient httpClient = new HttpClient();
            await httpClient.PostAsync(url, null);
        }

        /// <summary>
        /// 关闭退出爱奇艺
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            await Logout();
        }

        private async void btndelay_Click(object sender, EventArgs e)
        {
            IQIYISeckill seckill = (IQIYISeckill)(cbSeckill.SelectedItem);

            using HttpClient httpClient = new HttpClient();

            IqiyiBaseParam iqiyiBaseParam = new IqiyiBaseParam()
            {
                P00001 = loginResult?.authcookie
            };
            var dic = IqiyiFun.ObjectToMap(iqiyiBaseParam);
            dic.Add("code", seckill.Code);
            string url = $"https://act.vip.iqiyi.com/supermk/seckill/action/seckill?{IqiyiFun.DicToGetString(dic)}";

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            var res = await httpClient.PostAsync(url, null);
            TimeSpan difference = (DateTime.Now - res.Headers.Date).Value;
            stopwatch.Stop();
            await SetTxtMsg($"毫秒：{difference.TotalMilliseconds},{stopwatch.ElapsedMilliseconds}");
            await SetTxtMsg($"毫秒：{difference.TotalMilliseconds - stopwatch.ElapsedMilliseconds}");


        }

    }
}
